package com.ihome.android.image.impl;

import android.os.Build;
import android.util.Log;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * A simple class that fetches images from a URL.
 */
public class SimpleDownloader {

	private static final String	TAG						= "image_provider";

	private static final int	IO_BUFFER_SIZE			= 64 * 1024;

	private static final int	SET_CONNECTION_TIMEOUT	= 2500;
	private static final int	SET_SOCKET_TIMEOUT		= 5000;

	/**
	 * Download a bitmap from a URL and write the content to an output stream.
	 * 
	 * @param urlString
	 *            The URL to fetch
	 * @return true if successful, false otherwise
	 */
	public static boolean downloadUrlToStream(String urlString, OutputStream outputStream, boolean retry) {
		disableConnectionReuseIfNecessary();
		HttpURLConnection urlConnection = null;
		BufferedOutputStream out = null;
		BufferedInputStream in = null;

		//Log.v(TAG, "downloadUrlToStreamp() --> retry = " + retry + "; url = " + urlString);

		try {
			final URL url = new URL(urlString);
			urlConnection = (HttpURLConnection) url.openConnection(java.net.Proxy.NO_PROXY);
			urlConnection.setConnectTimeout(SET_CONNECTION_TIMEOUT);
			urlConnection.setReadTimeout(SET_SOCKET_TIMEOUT);

			in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE);
			out = new BufferedOutputStream(outputStream, IO_BUFFER_SIZE);

			int b;
			while ((b = in.read()) != -1) {
				out.write(b);
			}
			return true;
		} catch (final Exception e) {
			if (retry) {
				return downloadUrlToStream(urlString, outputStream, false);
			}
			Log.e(TAG, "Error in downloadBitmap - " + e);
		} finally {
			if (urlConnection != null) {
				urlConnection.disconnect();
			}
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (final IOException e) {}
		}
		return false;
	}

	/**
	 * Workaround for bug pre-Froyo, see here for more info:
	 * http://android-developers.blogspot.com/2011/09/androids-http-clients.html
	 */
	public static void disableConnectionReuseIfNecessary() {
		// HTTP connection reuse which was buggy pre-froyo
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
			System.setProperty("http.keepAlive", "false");
		}
	}
}
